/**
 * @author Eddie
 * @date 2023-10-24
 * 长者风采相关接口(对外提供，例如大屏)
 */

const router = require('koa-router')();
const fs = require('fs');

// 定义路由前缀，没有可不添加
router.prefix('/api/zzfc');

// router.get('/getImages', async (ctx, next) => {
//   let dirList = fs.readdirSync('./images/zzfc');
//   ctx.body = {
//     "code": 1,
//     "data": {
//       "url": "http://" + ctx.host,
//       "list": dirList
//     }
//   }
// })

router.post('/upload', async (ctx, next) => {
  try {
    const file = ctx.request.files.avatar; // 获取上传文件
    // 创建可读流
    const reader = fs.createReadStream(file.filepath);
    const fileResource = './images/zzfc/' + file.originalFilename;
    // 创建可写流
    const upStream = fs.createWriteStream(fileResource);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);

    ctx.body = {
      code: 1,
      data: {
        host: "http://" + ctx.host + "/images",
        url: "/zzfc/" + file.originalFilename
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      data: {}
    }
  }
})

// 获取长者风采信息
router.get('/getZzfc', async (ctx, next) => {
  try {
    let klhdObj = fs.readFileSync('./files/zzfc.json', 'utf8');
    let returnObj = {};
    returnObj["list"] = JSON.parse(klhdObj)

    returnObj["host"] = "http://" + ctx.host + "/images";

    ctx.body = {
      code: 1,
      msg: "读取成功",
      data: returnObj
    }
  } catch (error) {
    console.log("getZzfc", error);
    ctx.body = {
      code: -1,
      msg: "读取失败：" + error,
      data: {}
    }
  }
})

// 添加长者风采
router.post('/addZzfc', async (ctx, next) => {
  let data = ctx.request.body;
  let re = {};

  for (const item in data) {
    if (data[item]) {
      if (data[item]["url"] && data[item]["url"] != "") {
        data[item]["url"] = data[item]["url"].split("images")[1];
      }
    }
  }

  try {
    fs.writeFileSync('./files/zzfc.json', JSON.stringify(data));
    console.log("写入 zzfc.js 成功");

    re = {
      code: 1,
      msg: "写入成功"
    }
  } catch (error) {
    console.log("写入失败" + error);

    re = {
      code: -1,
      msg: "写入失败" + error
    }
  }

  ctx.body = re;
})

module.exports = router;